package org.particlethink.auth;

import org.particlethink.customer.Consumer;
import org.particlethink.entry.RoleTyp;
import org.particlethink.model.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.Collections;
import java.util.Objects;
import java.util.Optional;

public class DefaultUser implements UserDetails, Consumer {
    private User user;

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {// 用户的功能权限
        return Collections.singletonList(new SimpleGrantedAuthority(".*"));
    }

    @Override
    public String getPassword() { // 系统中的用户密码验证永远都是成功的，如果用户验证失败应该在通过用户名加载用户信息时跑出对应的异常
        return "123456";
    }

    public String getUsername() {
        return this.user.getUsername();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() { // 返回的用户信息始终可用
        return true;
    }

    @Override
    public RoleTyp findRole() {
        if (isCompanyConsumer()) {
            return RoleTyp.Company;
        }
        if (isProjectConsumer()) {
            return RoleTyp.Project;
        }
        if (isSupplierConsumer()) {
            return RoleTyp.Supplier;
        }
        return null;
    }

    @Override
    public boolean isCompanyConsumer() {
        return Objects.equals(this.user.getUserType(), "公司");
    }

    @Override
    public boolean isSupplierConsumer() {
        return Objects.equals(this.user.getUserType(), "供应商");
    }

    @Override
    public boolean isProjectConsumer() {
        return Objects.equals(this.user.getUserType(), "项目");
    }

    @Override
    public Integer getProjectId() {
        return Optional.ofNullable(this.user.getProjectIds()).orElseGet(() -> Collections.singletonList(0)).get(0);
    }

    @Override
    public Integer getSupplierId() {
        return Optional.ofNullable(this.user.getSupplierIds()).orElseGet(() -> Collections.singletonList(0)).get(0);
    }

    @Override
    public Integer getUserId() {
        return getUser().getUserId();
    }
}
